package common

import (
	"context"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/parnurzeal/gorequest"
)

const (
	GFYX_MODEL_API_HOST  = "gfyx_model_api_host"
	GFYX_MODEL_API_APPID = "gfyx_model_api_appid"
	GFYX_MODEL_API_KEY   = "gfyx_model_api_key"
)

// 这个建模http组件暂时不替换成公共库的组件，鉴权使用方式不同
type GfyxModelApiHttpClient struct {
	client *http_client.HttpClientTool
}

// NewGfyxModelApiHttpClient
// 采购平台供应商开放服务http client工具类
func NewGfyxModelApiHttpClient() *GfyxModelApiHttpClient {
	return &GfyxModelApiHttpClient{
		client: http_client.New(),
	}
}

// Get
// 建模java api服务Get请求
func (c *GfyxModelApiHttpClient) Get(ctx context.Context, path, tenantCode string, params map[string]interface{}, header map[string]string) *GfyxModelApiHttpClient {
	url := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(GFYX_MODEL_API_HOST, "") + path
	url = JoinQueryStr(url, params)
	header = c.setCommonHeader(tenantCode, header)

	c.client = c.client.Get(ctx, url, header)
	return c
}

// Post
// 建模java api服务Post请求
func (c *GfyxModelApiHttpClient) Post(ctx context.Context, path, tenantCode string, params map[string]interface{}, header map[string]string) *GfyxModelApiHttpClient {
	url := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(GFYX_MODEL_API_HOST, "") + path

	header = c.setCommonHeader(tenantCode, header)

	// todo 组织获取
	//if path == "/pub/Mysoft.PubPlatform.Organization.PublicServices.IRoleAclPublicService/GetUserActionRightInfos" {
	//	c.client = c.client.Post(ctx, url, "\"4230bc6e-69e6-46a9-a39e-b929a06a84e8\"", header)
	//	return c
	//}
	c.client = c.client.Post(ctx, url, params, header)
	return c
}

func (c *GfyxModelApiHttpClient) setCommonHeader(tenantCode string, header map[string]string) map[string]string {
	if header == nil {
		header = map[string]string{}
	}
	key := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(GFYX_MODEL_API_APPID, "")
	secret := stark.Configer.(stark.ApolloConfigerIface).GetStringValue(GFYX_MODEL_API_KEY, "")
	//fmt.Sprintf("key: %s, se: %s", key, secret)
	header["appid"] = key
	header["appkey"] = secret
	if tenantCode != "" {
		header["tenantCode"] = tenantCode
		header["_my-skyline-yunerp-tenantcode_"] = tenantCode
	}

	return header
}

// EndStruct
// convert interface(v) to struct
func (c *GfyxModelApiHttpClient) EndStruct(v interface{}) (gorequest.Response, []byte, []error) {
	return c.client.EndStruct(v)
}
